<?php

namespace App\Http\Model;

/**
 * @desc 格式化json 数据
 * Class OutJson
 * @package app\api\service
 */

class OutJson
{
    /**
     * @desc 返回带数据的json string
     * @param $code
     * @param array $data
     * @param string $format
     */
    static function outJsonResult($code, $data = array(), $format = 'data')
    {
        $res['code'] = $code;
        if ($code == -1) {
            header('HTTP/1.1 500 Internal Server Error');
        }
        $res['msg'] = isset(Hint::$Msg[$code]) ? Hint::$Msg[$code] : '失败';

        $format = empty($format) ? 'data' : $format;

        $res[$format] = $data;

        if ($code != 0 && empty($data)) {
            unset($res[$format]);
        }

        $callback = empty($_GET['callback']) ? '' : trim($_GET['callback']);
        $jsonStr = json_encode($res, JSON_UNESCAPED_UNICODE);
        if (empty($callback)) {
            echo $jsonStr;
            exit;
        } else {
            echo "{$callback}(" . $jsonStr . ")";
            exit;
        }

    }

    /**
     * @desc 返回没有数据的json string
     * @param $code
     * @param array $data
     * @param string $format
     */
    static function outJsonNoData($code, $data = array(), $format = 'data')
    {

        $res['code'] = $code;
        if ($code == -1) {
            header('HTTP/1.1 500 Internal Server Error');
        }
        $res['msg'] = isset(Hint::$Msg[$code]) ? Hint::$Msg[$code] : '失败';

        $format = empty($format) ? 'data' : $format;

        if ($data) {
            $res[$format] = $data;
        } else {

        }

        $callback = empty($_GET['callback']) ? '' : trim($_GET['callback']);
        $jsonStr = json_encode($res, JSON_UNESCAPED_UNICODE);
        if (empty($callback)) {
            echo $jsonStr;
        } else {
            echo "{$callback}(" . $jsonStr . ")";
        }

        exit;
    }

    static function toJson($code = -1, $message = '成功', $data = [])
    {
        echo json_encode(['code' => $code, 'data' => $data, 'message' => $message]);
        exit;
    }

}
